package org.jeecg.modules.demo.demo.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.demo.demo.entity.*;
import org.jeecg.modules.demo.demo.service.IPuContractService;
import org.jeecg.modules.demo.pubuyorder.entity.PuBuyOrder;
import org.jeecg.modules.demo.pubuyorder.service.IPuBuyOrderService;
import org.jeecg.modules.demo.yxtraderdata.entity.YxTraderData;
import org.jeecg.modules.demo.yxtraderdata.service.IYxTraderDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: Onism-Aug
 * @Date: 2021/12/2 16:29
 * @Describe:
 */
@RestController
@RequestMapping("/api/contront")
@Slf4j
public class controntApi {
    @Autowired
    private IPuContractService puContractService;
    @Autowired
    private IYxTraderDataService yxTraderDataService;
    @Autowired
    private IPuBuyOrderService puBuyOrderService;

    /**
     * 合同查询
     */
    @PostMapping(value = "/queryHetglinfo")
    public Result<?> queryHetglinfo(@RequestParam(name="json",required=true) String json) {
        try{
            Gson gson = new Gson();
            VEcpHetglinfoEntity hetglinfo = gson.fromJson(json, VEcpHetglinfoEntity.class);
            if(hetglinfo.getHetlrbh()==null || hetglinfo.getHetlrbh().isEmpty()){
                log.info("合同查询： "+ DateUtils.now()+"：The internal number of the contract cannot be empty-----HTNBBHWK");
                return Result.error(300,"The internal number of the contract cannot be empty");
            }
            QueryWrapper<PuContract> queryWrapper=new QueryWrapper();
            queryWrapper.eq("HETLRBH",hetglinfo.getHetlrbh());
            PuContract puContract1 = puContractService.getOne(queryWrapper);
            if(puContract1!=null ){
                log.info("合同查询： "+ DateUtils.now()+"：Contract exists-----HTCZ");
                return Result.OK("Contract exists");
            }else {
                log.info("合同查询： "+ DateUtils.now()+"：The contract data does not exist------HTBCZ");
                return Result.error(302,"Contract data does not exist");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(500,"fail");
        }
    }


    /**
     * 合同退回
     */
    @PostMapping(value = "/returnHetglinfo")
    public Result<?> returnHetglinfo(@RequestParam(name="json",required=true) String json) {
        try{
            Gson gson = new Gson();
            VEcpHetglinfoEntity hetglinfo = gson.fromJson(json, VEcpHetglinfoEntity.class);
            if(hetglinfo.getHetlrbh()==null || hetglinfo.getHetlrbh().isEmpty()){
                log.info("合同退回： "+ DateUtils.now()+"：The internal number of the contract cannot be empty-----HTNBBHWK");
                return Result.error(300,"The internal number of the contract cannot be empty");
            }
            QueryWrapper<PuContract> queryWrapper=new QueryWrapper();
            queryWrapper.eq("HETLRBH",hetglinfo.getHetlrbh());
            PuContract puContract1 = puContractService.getOne(queryWrapper);
            if(puContract1!=null ){
                if(!puContract1.getStatus().equals("0")){
                    log.info("合同退回:" + DateUtils.now() + "已生成订单，无法退回合同");
                    return Result.error(333,"合同已生成订单，无法退回合同!");
                }else{
                    PuBuyOrder puBuyOrder = puBuyOrderService.getPuBuyOrderByHetbh(puContract1.getHetlrbh());
                    if(puBuyOrder!=null){
                        log.info("合同退回： "+ DateUtils.now()+"：The contract has generated an order and cannot be returned-----HTCSDD");
                        return Result.error(301,"The contract has generated an order and cannot be returned！");
                    }else{
                        log.info("合同退回： "+ DateUtils.now()+"：Contract exists, successfully returned-----HTCZ");
                        puContractService.removeById(puContract1.getId());
                        return Result.OK("Contract returned successfully");
                    }
                }
            }else {
                log.info("合同退回： "+ DateUtils.now()+"：The contract data does not exist------HTBCZ");
                return Result.error(302,"Contract data does not exist, contract return failed");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(500,"fail");
        }
    }


    /**
     * VEcpHetglinfoEntity-----------公路
     */
    @PostMapping(value = "/saveHetglinfo")
    public Result<?> saveHetglinfo(@RequestParam(name="json",required=true) String json) {
        try{
            Gson gson = new Gson();
            PuContract puContract = new PuContract();
            VEcpHetglinfoEntity hetglinfo = gson.fromJson(json, VEcpHetglinfoEntity.class);
            if(hetglinfo.getHetlrbh()==null || hetglinfo.getHetlrbh().isEmpty()){
                log.info("Highway contract： "+ DateUtils.now()+"：The internal number of the contract cannot be empty！G 1");
                return Result.error(500,"The internal number of the contract cannot be empty！");
            }
            QueryWrapper<PuContract> queryWrapper=new QueryWrapper();
            queryWrapper.eq("HETLRBH",hetglinfo.getHetlrbh());
            PuContract puContract1 = puContractService.getOne(queryWrapper);
            if(puContract1!=null ){
                log.info("Highway contract： "+ DateUtils.now()+"：The contract data already exists！G 2");
                return Result.error(500,"The contract data already exists！");
            }else {
                puContract.setPuConNo(replaceBlank(hetglinfo.getHetbh()));
                puContract.setPjsNo(hetglinfo.getChumdwbm());
                puContract.setPoOrder(String.valueOf(hetglinfo.getToid()));
                puContract.setCustName(hetglinfo.getSectorname());
                puContract.setCustAdress(hetglinfo.getChumdwdz());
                puContract.setCustTotal(hetglinfo.getShul().doubleValue());
                if (Integer.parseInt(hetglinfo.getSfxs()) == 0) {
                    puContract.setCustAmount(Double.valueOf(hetglinfo.getJiag().toString()));
                } else {
                    puContract.setCustAmount(Double.valueOf(hetglinfo.getYcjiag().toString()));
                }
                puContract.setSupBank(hetglinfo.getChumdwkhyh());
                puContract.setSupBanknum(hetglinfo.getChumdwzh());
                puContract.setSectorname(hetglinfo.getSectorname());
                puContract.setPinp(replaceBlank(hetglinfo.getPinp()));
                puContract.setMaisdwmc(hetglinfo.getMaisdwmc());
                puContract.setChumdwmc(hetglinfo.getChumdwmc());
                puContract.setHetbh(replaceBlank(hetglinfo.getHetbh()));
                puContract.setCreateTime(new Date());
                puContract.setStatus("0");
                puContract.setTransport("公路");
                puContract.setZhilzbjson(hetglinfo.getZhilzbjson());
                puContract.setZhilzb(hetglinfo.getZhilzb());
                puContract.setUnit(hetglinfo.getUnit());
                puContract.setFazbm(hetglinfo.getFazbm());
                puContract.setDaozbm(hetglinfo.getDaozbm());
                puContract.setHetlrbh(replaceBlank(hetglinfo.getHetlrbh()));
                puContract.setQysj(hetglinfo.getZidqysj());
                puContractService.save(puContract);
                return Result.OK("success！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(500,"fail！");
        }
    }




    /**
     * VEcpHetinfoEntity-----------铁路
     */
    @PostMapping(value = "/saveHetinfo")
    public Result<?> saveHetinfo(@RequestParam(name="json",required=true) String json) {
        try{
            Gson gson = new Gson();
            PuContract puContract = new PuContract();
            VEcpHetinfoEntity hetglinfo = gson.fromJson(json, VEcpHetinfoEntity.class);

            if(hetglinfo.getHetlrbh()==null || hetglinfo.getHetlrbh().isEmpty()){
                log.info("Railway Contract： "+ DateUtils.now()+"：The internal number of the contract cannot be empty！T 1");
                return Result.error(500,"The internal number of the contract cannot be empty！");
            }
            QueryWrapper<PuContract> queryWrapper=new QueryWrapper();
            queryWrapper.eq("HETLRBH",hetglinfo.getHetlrbh());
            PuContract puContract1 = puContractService.getOne(queryWrapper);
            if(puContract1!=null){
                log.info("Railway Contract： "+ DateUtils.now()+"：The contract data already exists！T 2");
                return Result.error(500,"The contract data already exists！");
            }else {
                puContract.setPuConNo(replaceBlank(hetglinfo.getHetbh()));
                puContract.setPjsNo(hetglinfo.getChumdwbm());
                puContract.setPoOrder(String.valueOf(hetglinfo.getToid()));
                puContract.setCustName(hetglinfo.getSectorname());
                puContract.setCustAdress(hetglinfo.getChumdwdz());
                puContract.setCustTotal(hetglinfo.getShul().doubleValue());

                if(Integer.parseInt(hetglinfo.getSfxs())==0){
                    puContract.setCustAmount(Double.valueOf(hetglinfo.getJiag().toString()));
                }else{
                    puContract.setCustAmount(Double.valueOf(hetglinfo.getYcjiag().toString()));
                }

                puContract.setSupBank(hetglinfo.getChumdwkhyh());
                puContract.setSupBanknum(hetglinfo.getChumdwzh());
                puContract.setSectorname(hetglinfo.getSectorname());
                puContract.setPinp(replaceBlank(hetglinfo.getPinp()));
                puContract.setMaisdwmc(hetglinfo.getMaisdwmc());
                puContract.setChumdwmc(hetglinfo.getChumdwmc());
                puContract.setHetbh(replaceBlank(hetglinfo.getHetbh()));
                puContract.setCreateTime(new Date());
                puContract.setStatus("0");
                puContract.setTransport("铁路");
                puContract.setZhilzbjson(hetglinfo.getZhilzbjson());
                puContract.setZhilzb(hetglinfo.getZhilzb());
                puContract.setUnit(hetglinfo.getUnit());
                puContract.setFazbm(hetglinfo.getFazbm());
                puContract.setDaozbm(hetglinfo.getDaozbm());
                puContract.setHetlrbh(replaceBlank(hetglinfo.getHetlrbh()));
                puContract.setQysj(hetglinfo.getZidqysj());
                puContractService.save(puContract);
                return Result.OK("success！");
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(500,"fail！");
        }
    }


    /**
     * VEcpHetslinfoEntity-----------水路
     */
    @PostMapping(value = "/saveHetslinfo")
    public Result<?> saveHetslinfo(@RequestParam(name="json",required=true) String json) {
      try{
          Gson gson = new Gson();
          PuContract puContract = new PuContract();
          VEcpHetslinfoEntity hetglinfo = gson.fromJson(json, VEcpHetslinfoEntity.class);
          if(hetglinfo.getHetlrbh()==null || hetglinfo.getHetlrbh().isEmpty()){
              log.info("Waterway contract： "+ DateUtils.now()+"：The internal number of the contract cannot be empty！S 1");
              return Result.error(500,"The internal number of the contract cannot be empty！");
          }
          QueryWrapper<PuContract> queryWrapper=new QueryWrapper();
          queryWrapper.eq("HETLRBH",hetglinfo.getHetlrbh());
          PuContract puContract1 = puContractService.getOne(queryWrapper);
          if(puContract1!=null ){
              log.info("Waterway contract： "+ DateUtils.now()+"：The contract data already exists！S 2");
              return Result.error(500,"The contract data already exists！");
          }else {
//          puContract.setId(hetglinfo.getHetid());
              puContract.setPuConNo(replaceBlank(hetglinfo.getHetbh()));
              puContract.setPjsNo(hetglinfo.getChumdwbm());
              puContract.setPoOrder(String.valueOf(hetglinfo.getToid()));
              puContract.setCustName(hetglinfo.getSectorname());
              puContract.setCustAdress(hetglinfo.getChumdwdz());
              puContract.setCustTotal(hetglinfo.getShul().doubleValue());
              if (Integer.parseInt(hetglinfo.getSfxs()) == 0) {
                  puContract.setCustAmount(Double.valueOf(hetglinfo.getJiag().toString()));
              } else {
                  puContract.setCustAmount(Double.valueOf(hetglinfo.getYcjiag().toString()));
              }
              puContract.setSupBank(hetglinfo.getChumdwkhyh());
              puContract.setSupBanknum(hetglinfo.getChumdwzh());
              puContract.setSectorname(hetglinfo.getSectorname());
              puContract.setPinp(replaceBlank(hetglinfo.getPinp()));
              puContract.setMaisdwmc(hetglinfo.getMaisdwmc());
              puContract.setChumdwmc(hetglinfo.getChumdwmc());
              puContract.setHetbh(replaceBlank(hetglinfo.getHetbh()));
              puContract.setCreateTime(new Date());
              puContract.setStatus("0");
              puContract.setTransport("水路");
              puContract.setZhilzbjson(hetglinfo.getZhilzbjson());
              puContract.setZhilzb(hetglinfo.getZhilzb());
              puContract.setUnit(hetglinfo.getUnit());
              puContract.setFazbm(hetglinfo.getFazbm());
              puContract.setDaozbm(hetglinfo.getDaozbm());
              puContract.setHetlrbh(replaceBlank(hetglinfo.getHetlrbh()));
              puContract.setQysj(hetglinfo.getZidqysj());
              puContractService.save(puContract);
              return Result.OK("success！");
          }
      }catch (Exception e){
          e.printStackTrace();
          return Result.error(500,"fail！");
      }
    }
    @PostMapping(value = "/saveTrader")
    public Result<?> saveTrader(@RequestParam(name="json",required=true) String json){
        try{
            Gson gson = new Gson();
            TraderEntity traderEntity = gson.fromJson(json, TraderEntity.class);
            List<String> teantidList = yxTraderDataService.getTeantId();
            for (String s : teantidList) {
                YxTraderData yxTraderData = new YxTraderData();
                yxTraderData.setTraderid(traderEntity.getTraderid());
                yxTraderData.setFullname(traderEntity.getFullname());
                yxTraderData.setAbbrname(traderEntity.getAbbrname());
                yxTraderData.setLegallyar(traderEntity.getLegallyar());
                yxTraderData.setIndustryid(traderEntity.getIndustryid());
                yxTraderData.setTraderauthstatus(traderEntity.getTraderauthstatus());
                yxTraderData.setAddtime(traderEntity.getAddtime());
                yxTraderData.setCreateTime(new Date());
                yxTraderData.setAddmethod(1);
                yxTraderData.setTenantId(Integer.parseInt(s));
                Integer inteher = yxTraderDataService.getByTeantId(yxTraderData);
                if(inteher>1){
                    continue;
                }else {
                    yxTraderDataService.save(yxTraderData);
                }
            }

            return Result.OK("success！");
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(500,"fail！");
        }
    }


    public static String replaceBlank(String str) {

        String dest = "";

        if (str != null) {

            Pattern p = Pattern.compile("\\s*|\t|\r|\n");

            Matcher m = p.matcher(str);

            dest = m.replaceAll("");

        }

        return dest;

    }

    //通过买方和卖方查询是否是贸易煤的租户
    @PostMapping(value = "/isMymLessee")
    public String isZcmFirm(@RequestParam(name="maisdwmc",required=true) String maisdwmc,
                            @RequestParam(name="chumdwmc",required=true) String chumdwmc) {

        List<Map<String,String>> departList = this.puContractService.getisMymLessee(maisdwmc, chumdwmc);
        if(departList.size() > 0){
            return "1";
        }else{
            return "0";
        }
    }


}
